package com.gframework.mybatis.service.impl;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;

import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gframework.mybatis.dao.IPrimaryDAO;
import com.gframework.mybatis.dao.ITableBasicDAO;
import com.gframework.mybatis.dao.mybatis.provider.ProviderUtils;
import com.gframework.mybatis.service.IService;
import com.gframework.mybatis.service.ITableService;
import com.gframework.mybatis.service.IViewService;

/**
 * 基于本套mybatis框架的service通用操作父类.
 * 
 * @since 2.0.0
 * @author Ghwolf
 * 
 * @see ITableService
 * @see IViewService
 * @see IService
 * @see TableServiceImpl
 * @see ViewServiceImpl
 * 
 * @param <M> 当前操作对应的dao接口类型
 * @param <K> 实体类主键类型
 * @param <T> 实体类类型
 */
public class ServiceImpl<M extends ITableBasicDAO<T> & IPrimaryDAO<K, T>, K extends Serializable, T extends Serializable>
		extends TableServiceImpl<M, T> implements IService<M, K, T> {

	@Override
	public T get(K id) {
		if (id == null) return null ;
		return getDao().findById(id);
	}

	@Override
	@Transactional
	public int delete(K id) {
		if (id == null) return 0 ;
		return getDao().deleteById(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public int delete(K... ids) {
		if (ids == null || ids.length == 0) return 0 ;
		return getDao().deleteByIds(Arrays.asList(ids));
	}

	@Override
	@Transactional
	public int delete(Collection<K> ids) {
		if (ids == null || ids.isEmpty()) return 0 ;
		return getDao().deleteByIds(ids);
	}

	@Override
	@Transactional
	public boolean update(T pojo) {
		Assert.notNull(pojo,"pojo 不能为null！");
		return getDao().updateById(pojo) != 1 ;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public boolean saveOrUpdate(T pojo) {
		Assert.notNull(pojo,"pojo 不能为null！");
		String pkFieldName = ProviderUtils.getPojoInfo(pojo.getClass()).getPkFieldName();
		if (pkFieldName == null) {
			getDao().save(pojo);
			return true ;
		}
		
		K id = (K) getConfiguration().newMetaObject(pojo).getValue(pkFieldName);
		if (id == null) {
			getDao().save(pojo);
			return true ;
		}
		
		T t = getDao().findById(id);
		if (t == null) {
			getDao().save(pojo);
			return true ;
		} else {
			BeanUtils.copyProperties(pojo, t);
			getDao().updateById(t);
			return false;
		}
	}

	
}
